//
//  DeviceListController.m
//  DYLYJ
//
//  Created by JM on 15/10/23.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "DeviceListController.h"
#import "DeviceCell.h"
#import "DYArrayDataSource.h"
#import "DYUIKit.h"
#import "DeviceDetailController.h"
#import "LoginController.h"
#import "DYNavigationCOntroller.h"
#import "SetPwdOfSSIDController.h"
#import "SettingController.h"
#import "AppDelegate.h"
#import "DYServer.h"
#import "DYRequestAll.h"
#import "DYUIKit.h"
#import "NSOBject+runtime.h"
#import <Masonry.h>
@interface DeviceListController ()<UITableViewDelegate,XPGWifiSDKDelegate,XPGWifiDeviceDelegate>
@property(nonatomic, strong) NSMutableArray     *devices;
@property(nonatomic, strong) DYArrayDataSource  *devicesDataSource;
@property(nonatomic, strong)UIRefreshControl *control;
@property(nonatomic, strong)NSTimer *timer;
@end

@implementation DeviceListController



-(void)setupRefresh
{
    //1.添加刷新控件
    UIRefreshControl *control=[[UIRefreshControl alloc]init];
    [control addTarget:self action:@selector(requestDeviceList) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:control];
    self.control = control;
}

-(void)requestDeviceList
{
    
    [self.control endRefreshing];
    
    if (myAppDelegate.isDemo && [DYArrayDataSource sharedDYArrayDataSource].count == 0){
        Device *device1 = [Device deviceWithIcon:@"device_1" name:@"阳台晾衣架" state:@"设备打开" open:NO ];
        Device *device2 = [Device deviceWithIcon:@"device_2" name:@"天台晾衣架" state:@"设备打开 消毒" open:NO];
        Device *device3 = [Device deviceWithIcon:@"device_3" name:@"虚拟晾衣架" state:@"设备打开 消毒 风干 暖风" open:NO];
        Device *device4 = [Device deviceWithIcon:@"device_4" name:@"地下晾衣架" state:@"设备打开 消毒" open:NO];
        self.devices = [NSMutableArray arrayWithArray:@[device1,device2,device3,device4]];
        self.devicesDataSource = [DYArrayDataSource dataSourceWithItems:self.devices cellIdentifier:[DeviceCell ID] configCellBlock:^(DeviceCell *cell, Device *item) {
            cell.device = item;
        }];
        [self.devicesDataSource saveItems];
        [self.tableView reloadData];
    }
    
    if (myAppDelegate.isDemo)
        return;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [XPGWifiSDK sharedInstance].delegate = self;
    [[XPGWifiSDK sharedInstance] getBoundDevicesWithUid:myAppDelegate.uid token:myAppDelegate.token specialProductKeys:nil];
    
    self.timer = [NSTimer timerWithTimeInterval:30 block:^(NSTimer *timer) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MJAlertView showMessage:@"请求超时"];
        });
    } repeats:NO];
}
#pragma mark -

- (void)XPGWifiSDK:(XPGWifiSDK *)wifiSDK didDiscovered:(NSArray *)deviceList result:(int)result {
    [self.timer invalidate];
    self.timer = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
    if(result == XPGWifiError_NONE) {
        
        NSLog(@"设备列表%@",[deviceList valueForKeyPath:@"propertiesDic"] );
        NSLog(@"存储设备列表%@",[[DYArrayDataSource sharedDYArrayDataSource].items valueForKeyPath:@"propertiesDic"] );
        for(XPGWifiDevice *xpgdevice in deviceList) {
            xpgdevice.delegate = [DYArrayDataSource sharedDYArrayDataSource];
//            //更改
            BOOL found = [self.devicesDataSource itemSearchWithEqualBlock:^BOOL(Device *aItem){
                if ([aItem.macAddress isEqualToString:xpgdevice.macAddress]) {
                    [aItem setXpgDevice:xpgdevice];
                    aItem.isHidden = NO;
                    if ([aItem.xpgDevice isBind:myAppDelegate.uid]){
                        aItem.isHidden = NO;
                    } else {
                        aItem.isHidden = YES;
                    }
                    return YES;
                }
                return NO;
            }];
            //增加
            if (!found){
                NSLog(@"增加 address:%@",xpgdevice.macAddress);
                Device *device = [Device deviceWith:xpgdevice];
                [self.devicesDataSource insertObject:device atIndex:0];
                if ([device.xpgDevice isBind:myAppDelegate.uid]){
                    device.isHidden = NO;
                } else {
                    device.isHidden = YES;
                }
            }
            //删除
            [self.devicesDataSource itemSearchWithEqualBlock:^BOOL(Device *aItem){
                BOOL found = NO;
                for (XPGWifiDevice * xpgDevice in deviceList){
                    if ([xpgDevice.macAddress isEqualToString:aItem.macAddress]) {
                        found = YES;
                    }
                }
                if (!found || (!aItem.xpgDevice)) {
                    NSLog(@" 删除 address:%@ name:%@",xpgdevice.macAddress,aItem.name);
//                    [self.devicesDataSource removeItem:aItem];
                    aItem.isHidden = YES;
                }
                return NO;
            }];
        }
        
//        self.devicesDataSource = [DYArrayDataSource dataSourceWithItems:self.devices cellIdentifier:[DeviceCell ID] configCellBlock:^(DeviceCell *cell, Device *item) {
//            cell.device = item;
//        }];
        [self.devicesDataSource setAllxpgDeviceDelegateIsMyself];
        [self.devicesDataSource setAllDeviceDelegate:self];
        [self.devicesDataSource connectAndupdateAllDevice];
            [self.tableView reloadData];
    }else{
         [MJAlertView showMessage:[NSError dy_errorWithErrCode:result].dy_description];
        NSLog(@"设备列表获取失败");
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    
    [self.tableView reloadData];
    
    
    [self.devicesDataSource setAllxpgDeviceDelegateIsMyself];
    [self.devicesDataSource setAllDeviceDelegate:self];
    
    __weak DeviceListController *weakSelf = (DeviceListController *)self;
    
    AppDelegate* delegate = (AppDelegate*)([UIApplication sharedApplication].delegate);
    if (!delegate.islogin){
        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        LoginController* vc = [storyboard instantiateViewControllerWithIdentifier:@"LoginController"];
        DYNavigationCOntroller *naviVC = [[DYNavigationCOntroller alloc] initWithRootViewController:vc];
        [weakSelf presentViewController:naviVC animated:YES completion:^{
            
        }];
    } else {
        if (![[DYArrayDataSource sharedDYArrayDataSource].userID isEqualToString:myAppDelegate.uid]){
            [DYArrayDataSource sharedDYArrayDataSource].userID = myAppDelegate.uid;
            self.devicesDataSource = [DYArrayDataSource dataSourceFromSaveFileWithCellId:[DeviceCell ID] ConfigCellBlock:^(DeviceCell *cell, Device *item) {
                cell.device = item;
                if (item.isHidden) {
                    cell.hidden = YES;
                    cell.contentView.hidden = YES;
                }
                else {
                    cell.hidden = NO;
                    cell.contentView.hidden = NO;
                }

                if (![cell.contentView viewWithTag:999]){
                    UIImage* image = [UIImage imageNamed:@"cell_arraw"];
                    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                    imageView.tag = 999;
                    [cell.contentView addSubview:imageView];
                    
                    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.right.equalTo(cell.contentView).with.offset(-26);
                        make.centerY.equalTo(cell.contentView);
                        make.size.mas_equalTo(image.size);
                    }];
                }
            }];
            self.tableView.dataSource = self.devicesDataSource;
            [self.tableView reloadData];
        }
        [self requestDeviceList];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.tableView.backgroundColor = UIColorFromHexStr(@"#F6F1E8");
    
     [DYServer sharedDYServer].receiveDelegate = self;
    
    self.title = @"设备列表";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barItemWithImageName:@"settingBtn" Target:self action:@selector(clickSetting:)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem editBarItemWithTarget:self action:@selector(clickEdit:)];

    [self setupRefresh];
    [self.tableView registerNib:[UINib nibWithNibName:[DeviceCell xib] bundle:nil] forCellReuseIdentifier:[DeviceCell ID]];
    self.tableView.dataSource = [DYArrayDataSource sharedDYArrayDataSource];
    
//    [self setExtraCellLineHidden];
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [self.tableView setTableFooterView:view];
}

- (void)clickSetting:(id)sender {
    
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    SettingController* vc = [storyboard instantiateViewControllerWithIdentifier:@"SettingController"];
    DYNavigationCOntroller *naviVC = [[DYNavigationCOntroller alloc] initWithRootViewController:vc];
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];

}

- (void)clickAdd:(id)sender {
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    SetPwdOfSSIDController* vc = [storyboard instantiateViewControllerWithIdentifier:@"SetPwdOfSSIDController"];
    DYNavigationCOntroller *naviVC = [[DYNavigationCOntroller alloc] initWithRootViewController:vc];
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
   
}

- (void) addItem:(Device *)aItem {
    [self.devicesDataSource insertObject:aItem atIndex:0];
    [self.tableView reloadData];
//    [self.tableView updateWithBlock:^(UITableView *tableView) {
//         [self.tableView insertRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationRight];
//    }];
}

- (void)clickEdit:(id)sender {
    if (self.tableView.editing) {
        BOOL ddd= [self.devicesDataSource saveItems];
        //解绑
        for (Device *device in self.devicesDataSource.removedItems) {
            
            if([device.xpgDevice isBind:myAppDelegate.uid] && (!myAppDelegate.isDemo))
            {
                [[XPGWifiSDK sharedInstance] unbindDeviceWithUid:myAppDelegate.uid token:myAppDelegate.token did:device.xpgDevice.did passCode:device.xpgDevice.passcode];
            }
        }
        self.devicesDataSource.removedItems=nil;

        self.navigationItem.leftBarButtonItem = [UIBarButtonItem barItemWithImageName:@"settingBtn" Target:self action:@selector(clickSetting:)];
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem editBarItemWithTarget:self action:@selector(clickEdit:)];
        
    } else {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem barItemWithImageName:@"add_btn" Target:self action:@selector(clickAdd:)];
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barItemWithImageName:@"finish_btn" Target:self action:@selector(clickEdit:)];
    }
    
//    self.tableView.allowsSelection = YES;
    [self.tableView setEditing:![self.tableView isEditing] animated:YES];
}

#pragma mark -tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Device * device = [self.devicesDataSource itemAtIndex:indexPath.row];
    if (device.isHidden) {
        return 0;
    }
    return [DeviceCell height]  ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Device *device = [self.devicesDataSource itemAtIndex:indexPath.row];
    if (!device.xpgDevice.isOnline  &&(!myAppDelegate.isDemo)) {
        [MJAlertView showMessage:@"设备不在线"];
        return;
    }
    
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    DeviceDetailController* vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceDetailController"];
    vc.device = device;//[self.devicesDataSource itemAtIndex:indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - edit

- (nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) __TVOS_PROHIBITED;{
    return @"删除";
}


#pragma mark-上线离线回调
- (void)XPGWifiDevice:(XPGWifiDevice *)device didDeviceIsOnline:(BOOL)isOnline {
    
//   [self.tableView updateWithBlock:^(UITableView *tableView) {
       [self.tableView reloadData];
//   }];
}
- (void)XPGWifiDevice:(XPGWifiDevice *)device didLogin:(int)result {
//    [self.tableView updateWithBlock:^(UITableView *tableView) {
        [self.tableView reloadData];
//    }];
}

@end
